#include "PFactory.hh"
#include <math.h>

PFactory::PFactory(TimeoutQueue* AssignedQueue)
: Factory(AssignedQueue)
{
	if (!State)
		return;
	
	ResultOfEMA = 0;
}

ResultOf PFactory::hookWatchdog()
{
	USNumber PredictionNumOfWorker;
	PredictionNumOfWorker = predictNumOfWorker();
	
	if (PredictionNumOfWorker == Misprediction)
		return RETURN_OK;
	
	// TEST
// 	printf("Prediction = %d(%d)\n", 
// 		PredictionNumOfWorker, 
// 		InfoOfFactory->ListOfWorker->tellSize());
	
	if (PredictionNumOfWorker >= InfoOfFactory->tellMax())
		PredictionNumOfWorker = InfoOfFactory->tellMax();
	
	Number NeededNumOfWorker;
	NeededNumOfWorker = PredictionNumOfWorker - InfoOfFactory->ListOfWorker->tellSize();
	
	for (Number LC = 0; LC < NeededNumOfWorker; LC++)
		employ();
	
	return RETURN_OK;
}

USNumber PFactory::predictNumOfWorker()
{
	USNumber CurrentNumOfWorker;
	CurrentNumOfWorker = InfoOfFactory->ListOfWorker->tellSize();
	
	double PrevResultOfEMA;
	PrevResultOfEMA = calcEMA((double)CurrentNumOfWorker);
	
	if (PrevResultOfEMA >= ResultOfEMA)
		return Misprediction;
	
	return CurrentNumOfWorker + (CurrentNumOfWorker - floor(ResultOfEMA));
}

double PFactory::calcEMA(double InputVal)
{
	double PrevResultOfEMA;
	PrevResultOfEMA = ResultOfEMA;
	
	ResultOfEMA = Alpha * InputVal + (1 - Alpha) * PrevResultOfEMA;
	return PrevResultOfEMA;
}
